package services;

import java.util.Date;
import java.util.List;

import models.Resource;
import models.ResourceHierarchy;
import models.ResourceHierarchyPK;
import models.ResourceType;

public class TestSuiteService extends ResourceService {
	
	private static final String RESOURCE_DIRECTORY = "resources/testsuites/";
	
	private static TestSuiteService service;
	
	// Singleton pattern
	private TestSuiteService() {
	}
	
	public static TestSuiteService getService() {
		if (service == null) {
			service = new TestSuiteService();
		}
		return service;
	}
	
	public List<Resource> getAllTestSuites(long projectId) {
		return getChildResources(projectId, ResourceType.TestSuite);
	}
	
	public Resource getTestSuite(long testSuiteId) {
		return Resource.find.byId(testSuiteId);
	}
	
	public Resource getTestSuite(String testSuiteName) {
		return Resource.find.where().eq("name", testSuiteName).eq("type", ResourceType.TestSuite).findUnique();
	}
	
	public void saveTestSuite(long projectId, Resource testSuite) {
		if (testSuite.getId() <= 0) {
			createTestSuite(projectId, testSuite);
		} else {
			updateTestSuite(testSuite);
		}
	}
	
	private void createTestSuite(long projectId, Resource testSuite) {
		Date currentDate = new Date();
		testSuite.setType(ResourceType.TestSuite);
		testSuite.setCreateDate(currentDate);
		testSuite.setLastModified(currentDate);
		testSuite.save();
		testSuite.setResourcePath(RESOURCE_DIRECTORY + testSuite.getId());
		testSuite.save();
		
		ResourceHierarchyPK pk = new ResourceHierarchyPK();
		pk.setParentId(projectId);
		pk.setChildId(testSuite.getId());
		ResourceHierarchy rh = new ResourceHierarchy(pk);
		rh.save();
	}
	
	private void updateTestSuite(Resource testSuite) {
		testSuite.setLastModified(new Date());
		testSuite.save();
	}
	
	public void deleteTestSuites(long projectId) {
		List<Resource> testSuites = getAllTestSuites(projectId);
		for (Resource testSuite : testSuites) {
			testSuite.delete();
		}
		List<ResourceHierarchy> childResources = ResourceHierarchy.find.where().eq("parent_id", projectId).findList();
		for (ResourceHierarchy child : childResources) {
			child.delete();
		}
	}
	
}
